import React, { useState } from 'react';
import {
  Card,
  Steps,
  Form,
  Input,
  Select,
  InputNumber,
  Button,
  message,
  Row,
  Col,
  Table,
  Tag,
  Space,
  Typography,
  Alert,
  Slider,
  Result,
  Descriptions
} from 'antd';
import {
  InfoCircleOutlined,
  SlidersOutlined,
  GoldOutlined,
  EyeOutlined,
  SendOutlined
} from '@ant-design/icons';

const { Step } = Steps;
const { Option } = Select;
const { TextArea } = Input;
const { Title, Paragraph } = Typography;

const mockFunds = [
    { key: '1', code: '000001', name: '华夏成长混合', type: '混合型' },
    { key: '2', code: '000002', name: '易方达消费行业', type: '股票型' },
    { key: '3', code: '000006', name: '广发稳健增长', type: '混合型' },
    { key: '4', code: '510300', name: '沪深300ETF', type: '指数型' },
    { key: '5', code: '511010', name: '国债ETF', type: '债券型' },
    { key: '6', code: '161725', name: '招商中证白酒', type: '指数型' },
];

const CreatePortfolio = () => {
  const [current, setCurrent] = useState(0);
  const [form] = Form.useForm();
  const [selectedFunds, setSelectedFunds] = useState([]);
  const [weights, setWeights] = useState({});
  const [submitSuccess, setSubmitSuccess] = useState(false);

  const next = () => {
    form.validateFields().then(() => {
        if (current === 2) {
            const totalWeight = selectedFunds.reduce((sum, fund) => sum + (weights[fund.key] || 0), 0);
            if (totalWeight !== 100) {
                message.error('所有选中基金的权重总和必须为100%');
                return;
            }
        }
        setCurrent(current + 1);
    }).catch(err => console.log(err));
  };

  const prev = () => {
    setCurrent(current - 1);
  };

  const handleSubmit = () => {
    form.validateFields().then(values => {
      console.log('Form Values: ', values);
      console.log('Selected Funds: ', selectedFunds);
      console.log('Weights: ', weights);
      message.success('组合创建成功，已提交审核！');
      setSubmitSuccess(true);
    }).catch(err => console.log(err));
  };
  
  const handleSelectChange = (keys) => {
    const newSelectedFunds = mockFunds.filter(fund => keys.includes(fund.key));
    setSelectedFunds(newSelectedFunds);
  };

  const handleWeightChange = (key, value) => {
    setWeights(prev => ({ ...prev, [key]: value }));
  };

  const steps = [
    {
      title: '基础信息',
      icon: <InfoCircleOutlined />,
      content: (
        <>
          <Form.Item name="name" label="组合名称" rules={[{ required: true }]}>
            <Input placeholder="例如：稳健增长FOF组合" />
          </Form.Item>
          <Row gutter={16}>
            <Col span={12}>
                <Form.Item name="riskLevel" label="风险等级" rules={[{ required: true }]}>
                    <Select placeholder="请选择风险等级">
                    <Option value="low">低风险</Option>
                    <Option value="medium">中风险</Option>
                    <Option value="high">高风险</Option>
                    </Select>
                </Form.Item>
            </Col>
            <Col span={12}>
                 <Form.Item name="tags" label="产品特征标签" rules={[{ required: true }]}>
                    <Select
                      mode="tags"
                      placeholder="请选择或输入产品特征标签"
                      options={[
                        { value: '长期持有', label: '长期持有' },
                        { value: '价值投资', label: '价值投资' },
                        { value: '分散风险', label: '分散风险' },
                        { value: '稳健收益', label: '稳健收益' },
                        { value: '成长型', label: '成长型' },
                      ]}
                    />
                </Form.Item>
            </Col>
          </Row>
          <Form.Item name="description" label="组合描述" rules={[{ required: true }]}>
            <TextArea rows={4} placeholder="详细描述组合的投资理念、目标、适合人群等。" />
          </Form.Item>
        </>
      ),
    },
    {
      title: '策略与参数',
      icon: <SlidersOutlined />,
      content: (
        <>
            <Row gutter={16}>
                <Col span={12}>
                    <Form.Item name="strategy" label="核心策略" rules={[{ required: true }]}>
                        <Select placeholder="选择一个核心投资策略">
                        <Option value="asset_allocation">大类资产配置</Option>
                        <Option value="fof">FOF精选</Option>
                        <Option value="timing">行业轮动</Option>
                        <Option value="value">价值投资</Option>
                        </Select>
                    </Form.Item>
                </Col>
                <Col span={12}>
                     <Form.Item name="benchmark" label="业绩基准" rules={[{ required: true }]}>
                        <Select placeholder="选择一个业绩基准">
                            <Option value="csi300">沪深300指数</Option>
                            <Option value="csi500">中证500指数</Option>
                            <Option value="cbi">中证国债指数</Option>
                        </Select>
                    </Form.Item>
                </Col>
            </Row>
             <Row gutter={16}>
                <Col span={12}>
                    <Form.Item name="targetReturn" label="目标年化收益(%)" rules={[{ required: true }]}>
                        <InputNumber style={{ width: '100%' }} placeholder="例如：15" />
                    </Form.Item>
                </Col>
                <Col span={12}>
                     <Form.Item name="maxDrawdown" label="最大回撤容忍度(%)" rules={[{ required: true }]}>
                        <InputNumber style={{ width: '100%' }} placeholder="例如：10" />
                    </Form.Item>
                </Col>
            </Row>
        </>
      ),
    },
    {
      title: '选择基金及分配权重',
      icon: <GoldOutlined />,
      content: (
        <>
            <Table
                rowSelection={{
                    type: 'checkbox',
                    onChange: handleSelectChange,
                }}
                dataSource={mockFunds}
                columns={[
                    { title: '代码', dataIndex: 'code', key: 'code' },
                    { title: '名称', dataIndex: 'name', key: 'name' },
                    { title: '类型', dataIndex: 'type', key: 'type', render: t => <Tag color="blue">{t}</Tag> },
                ]}
                rowKey="key"
                pagination={false}
            />
            {selectedFunds.length > 0 && (
              <div style={{ marginTop: 24 }}>
                <h4>为每只已选基金分配权重（总和需为100%）</h4>
                {selectedFunds.map(fund => (
                  <div key={fund.key} style={{ display: 'flex', alignItems: 'center', marginBottom: 12 }}>
                    <span style={{ width: 180 }}>{fund.name}（{fund.code}）</span>
                    <InputNumber
                      min={0}
                      max={100}
                      value={weights[fund.key] || 0}
                      onChange={val => handleWeightChange(fund.key, val)}
                      style={{ width: 100, marginRight: 8 }}
                      placeholder="请输入权重"
                    />
                    <span>%</span>
                  </div>
                ))}
              </div>
            )}
            <Alert 
                style={{ marginTop: 20 }}
                message={`当前总权重: ${selectedFunds.reduce((sum, fund) => sum + (weights[fund.key] || 0), 0)}%`}
                type={selectedFunds.reduce((sum, fund) => sum + (weights[fund.key] || 0), 0) === 100 ? 'success' : 'error'}
                showIcon
            />
        </>
      ),
    },
    {
      title: '预览与提交',
      icon: <EyeOutlined />,
      content: (
          <Result
            status="success"
            title="组合配置完成！"
            subTitle="请仔细核对以下信息，确认无误后提交审核。"
            extra={[
                <Button type="primary" key="console" onClick={handleSubmit} icon={<SendOutlined/>}>
                    提交审核
                </Button>,
                <Button key="buy" onClick={prev}>返回修改</Button>,
            ]}
          >
            <div style={{ textAlign: 'left', background: '#fafafa', padding: 24 }}>
                <Descriptions title="组合信息概览" bordered>
                    <Descriptions.Item label="组合名称" span={3}>{form.getFieldValue('name')}</Descriptions.Item>
                    <Descriptions.Item label="风险等级">{form.getFieldValue('riskLevel')}</Descriptions.Item>
                    <Descriptions.Item label="核心策略">{form.getFieldValue('strategy')}</Descriptions.Item>
                    <Descriptions.Item label="业绩基准">{form.getFieldValue('benchmark')}</Descriptions.Item>
                    <Descriptions.Item label="成分基金" span={3}>
                       {selectedFunds.map(f => (
                           <Tag key={f.key} color="blue">{f.name} ({weights[f.key] || 0}%)</Tag>
                       ))}
                    </Descriptions.Item>
                </Descriptions>
            </div>
          </Result>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Title level={3}>创建组合产品</Title>
      <Paragraph type="secondary">
        由投顾自主创建基金组合产品，配置完成后将进入审核流程。
      </Paragraph>
      {submitSuccess && (
        <Alert message="组合创建成功，已提交审核！" type="success" showIcon style={{ marginBottom: 16 }} />
      )}
      <Card>
        <Steps current={current}>
          {steps.map(item => (
            <Step key={item.title} title={item.title} icon={item.icon} />
          ))}
        </Steps>
        <div style={{ marginTop: 24, minHeight: 300 }}>
          <Form form={form} layout="vertical">
            {steps[current].content}
          </Form>
        </div>
        <div style={{ marginTop: 24, textAlign: 'center' }}>
          {current < steps.length - 2 && (
            <Button type="primary" onClick={next}>
              下一步
            </Button>
          )}
          {current === steps.length - 2 && (
            <Button type="primary" onClick={next}>
                完成并预览
            </Button>
          )}
          {current > 0 && current < steps.length -1 && (
            <Button style={{ margin: '0 8px' }} onClick={prev}>
              上一步
            </Button>
          )}
        </div>
      </Card>
    </div>
  );
};

export default CreatePortfolio; 